﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EZMemoLib;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace Remember.WPF.Views
{
    /// <summary>
    /// Interaction logic for ItemCard.xaml
    /// </summary>
    public partial class ItemCard : UserControl
    {
        public event EventHandler OnFoundVoice;
        
        public MemoItem _Item;

        long _BookID = 0;
        public long BookID
        {
            set
            {
                _BookID = value;
                string loginID = (Context.Login != null) ? Context.Login.LoginID : string.Empty;
                player = Player.Instance( loginID, _BookID);
            }
        }

        public event EventHandler OnGoEdit;

        DoubleAnimation animFadeIn = new DoubleAnimation();
        DoubleAnimation animFadeOut = new DoubleAnimation();
        DoubleAnimation animFlash = null;

        public ItemCard()
        {
            InitializeComponent();

            this.imgSpeaking.Visibility = System.Windows.Visibility.Collapsed;

            mediaElement1.LoadedBehavior = MediaState.Manual;
            mediaElement1.UnloadedBehavior = MediaState.Manual;
            mediaElement1.MediaEnded += new RoutedEventHandler(mediaElement1_MediaEnded);
            mediaElement1.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElement1_MediaFailed);

            btnVoicePlay.Visibility = System.Windows.Visibility.Hidden ;
            btnVoiceStop.Visibility = System.Windows.Visibility.Hidden ;

            this.uiFirstShow.Visibility = System.Windows.Visibility.Hidden;
            this.uiLateShow.Visibility = System.Windows.Visibility.Hidden;

            this.partTimer.Tick += new EventHandler(partTimer_Tick);

            HideEditFeature();

            animFadeIn = new DoubleAnimation();
            animFadeIn.From = 0;
            animFadeIn.To = 1;
            animFadeIn.Duration = new Duration(TimeSpan.FromMilliseconds(1600));
            this.BeginAnimation(OpacityProperty, animFadeIn);

            animFadeOut = new DoubleAnimation();
            animFadeOut.From = 1;
            animFadeOut.To = 0;
            animFadeOut.Duration = new Duration(TimeSpan.FromMilliseconds(500));

            Duration duration = new Duration(TimeSpan.FromSeconds(0.6));

            animFlash = new DoubleAnimation
            {
                From = 1.0,
                To = 0.0,
                Duration = new Duration(TimeSpan.FromMilliseconds (800)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever

            };

        }

        void mediaElement1_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            this.imgSpeaking.BeginAnimation(OpacityProperty, animFadeOut);
        }

        void mediaElement1_MediaEnded(object sender, RoutedEventArgs e)
        {
            this.imgSpeaking.BeginAnimation(OpacityProperty, animFadeOut);
            partTimer.Stop();
        }

        void partTimer_Tick(object sender, EventArgs e)
        {
            StopVoice();
        }

        void HideAll()
        {
            uiFirstShow.Visibility = System.Windows.Visibility.Hidden;
            uiLateShow.Visibility = System.Windows.Visibility.Hidden;
        }

        void ShowFirst( )
        {
            uiFirstShow.Visibility = System.Windows.Visibility.Visible;
            uiFirstShow.BeginAnimation(OpacityProperty, animFadeIn);
            uiLateShow.Visibility = System.Windows.Visibility.Hidden;
        }

        void ShowLate()
        {
            uiLateShow.Visibility = System.Windows.Visibility.Visible;
            uiLateShow.BeginAnimation(OpacityProperty, animFadeIn);
        }

        void HideEditFeature()
        {
            if (Context.Login.LoginName != "haio")
            {
                this.btnEdit.Visibility = System.Windows.Visibility.Collapsed;
                this.btnStopItem.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        void ShowEditFeature()
        {
            //TODO: only author can edit
            if (Context.Login.LoginName != "haio")
                return;

            this.btnEdit.Visibility = System.Windows.Visibility.Visible;
            this.btnStopItem.Visibility = System.Windows.Visibility.Visible; 
        }

        string[] flowUnits;
        public void PlayItem(MemoItem item)
        {
            HideAll();
            _Item = item;

            if (_Item != null)
            {
                ShowEditFeature();

                if (!string.IsNullOrEmpty(_Item.ItemSound))
                {
                    btnVoicePlay.Visibility = System.Windows.Visibility.Visible;
                    btnVoiceStop.Visibility = System.Windows.Visibility.Visible;
                    if (OnFoundVoice != null)
                    {
                        OnFoundVoice(item, null);
                    }
                }

                string flowString = Context.ForceFlow;

                if (string.IsNullOrEmpty(flowString))
                {
                    flowString = _Item.ItemFlow;
                }

                if (string.IsNullOrEmpty(flowString))
                {
                    flowString = Context.DefaultFlow ;
                }

                flowUnits = flowString.Split ( '=');
                if (flowUnits != null && flowUnits.Length >= 2)
                {
                    if (!string.IsNullOrEmpty(flowUnits[0]))
                    {
                        foreach (var ch in flowUnits[0])
                        {
                            switch (ch.ToString().ToUpper())
                            {
                                case "S":
                                    PlayVoice();
                                    uiFirstShow.Text = _Item.ItemQuestion;
                                    uiLateShow.Text = _Item.ItemAnswer;

                                    break;
                                case "A":
                                    uiFirstShow.Text = _Item.ItemAnswer;
                                    uiLateShow.Text = _Item.ItemQuestion;
                                    ShowFirst();

                                    break;
                                case "D":
                                    break;
                                case "R":
                                    break;
                                case "P":
                                    break;

                                case "Q":
                                    uiFirstShow.Text = _Item.ItemQuestion;
                                    uiLateShow.Text = _Item.ItemAnswer;
                                    ShowFirst();

                                    break;
                            }
                        }
                    }
                }
                
                //SQ=A. Q=SA
            }
        }

        public void PlayLate()
        {
            if (_Item != null)
            {
                if (flowUnits != null && flowUnits.Length >= 2)
                {
                    if (!string.IsNullOrEmpty(flowUnits[1]))
                    {
                        foreach (var ch in flowUnits[1])
                        {
                            switch (ch.ToString().ToUpper())
                            {
                                case "S":
                                    PlayVoice();
                                    break;
                                case "A":
                                    ShowLate();
                                    break;
                                case "Q":
                                default:
                                    ShowLate();

                                    break;
                            }
                        }
                    }
                }
            }
        }

        public void End()
        {
            uiFirstShow.Text = string.Empty;
            uiLateShow.Text = string.Empty;
        }

        private void btnVoicePlay_Click(object sender, RoutedEventArgs e)
        {
            PlayVoice();
        }

        DispatcherTimer partTimer = new DispatcherTimer();
        Player player;

        void PlayVoice()
        {
            if ( _Item == null)
                return;

            string VoiceUrl = null;
            VoicePart part = player.GetVoicePartFromItem(_Item);
            if (part != null)
            {
                VoiceUrl = part.FilePath;
            }

            if (string.IsNullOrEmpty(VoiceUrl))
            {
                btnVoicePlay.IsEnabled = false;
                btnVoiceStop.IsEnabled = false; 
                return;
            }

            this.imgSpeaking.Visibility = System.Windows.Visibility.Visible ;
            this.imgSpeaking.BeginAnimation  (OpacityProperty, this.animFlash );

            mediaElement1.Source = new Uri(VoiceUrl, UriKind.Relative);
            mediaElement1.Play();
            
            TimeSpan ts = part.PartEnd  - part.PartStart ;
            if (ts != null && ts.TotalMilliseconds > 100)
            {
                mediaElement1.Position = part.PartStart;
                partTimer.Interval = ts;
                partTimer.Start();
            }
            else
            {
                mediaElement1.Position = part.PartStart;
            }
        }

        void StopVoice()
        {
            this.imgSpeaking.BeginAnimation(OpacityProperty, animFadeOut);
            mediaElement1.Stop();
            partTimer.Stop();

        }

        private void btnVoiceStop_Click(object sender, RoutedEventArgs e)
        {
            StopVoice();
        }

        public void Hide()
        {
            uiFirstShow.Text = string.Empty;
            uiLateShow.Text = string.Empty;
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            if (OnGoEdit != null)
            {
                OnGoEdit(this._Item , null);
            }
        }

        private void btnStopItem_Click(object sender, RoutedEventArgs e)
        {

        }

    }
}
